package com.mymail.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mymail.entity.Folder;
import com.mymail.entity.User;

;

public class FolderDAO extends DAOImp implements DAO {
	
	public int getCount(Integer folder_id) {
		String sql = "select mail_id from mail where folder_id=?";
		return getCount(sql, new Object[] { folder_id });
	}

	@SuppressWarnings("unchecked")
	public ArrayList getFoldersByUser(User user) {
		String sql = "select * from `folder` where user_id=?";
		return findArray(sql, new Object[] { user.getId() });
	}

	public boolean getByID(Integer id, Object obj) {
		Folder folder = (Folder) obj;
		return findOne("select * from `folder` where folder_id=?",
				new Object[] { id }, folder);
	}

	public boolean addNew(Object obj) {
		Folder folder = (Folder) obj;
		String sql = "insert into `folder` (folder_name,user_id,folder_other) values (?,?,?)";
		int i=insert(sql, new Object[] { folder.getName(), folder.getUser(),
				folder.getOther() });
		if(i>0){
			folder.setId(i);
			return true;
		}
		return false;
	}

	public boolean delete(Object obj) {
		Folder folder = (Folder) obj;
		String sql = "delete from `folder` where folder_id=?";
		return exe(sql, new Object[] { folder.getId() });
	}

	public boolean toDatabase(Object obj) {
		Folder folder = (Folder) obj;
		if (folder.getId() == null) {
			return addNew(folder);
		} else {
			return update(folder);
		}
	}

	public boolean update(Object obj) {
		Folder folder = (Folder) obj;
		String sql = "UPDATE `folder` SET folder_name=?,folder_other=? WHERE folder_id=?";
		return exe(sql, new Object[] { folder.getName(), folder.getOther(),
				folder.getId() });
	}

	protected Object getEntity(ResultSet result) throws SQLException {
		Folder folder = new Folder();
		setAtribute(result, folder);
		return folder;
	}

	protected void setAtribute(ResultSet result, Object obj)
			throws SQLException {
		Folder folder = (Folder) obj;
		folder.setId(result.getInt("folder_id"));
		folder.setName(result.getString("folder_name"));
		folder.setOther(result.getString("folder_other"));
		folder.setUser(result.getInt("user_id"));
		folder.setSort((char) result.getString("folder_sort").getBytes()[0]);
	}

}
